import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import Cookies from 'js-cookie';
import { useGetLangEffect, useGetThemeEffect, useGetSystemMessageEffect } from '@inbiz/render';
import { useApp, useEvents, getOfficialPreview, langToIntlKey } from '@inbiz/utils';
import SmallView from './components/SmallView';
import CardView from './components/CardView';
import SimpleView from './components/SimpleView';
import EditModal from './components/EditModal';
import { getUserInfoBytoken, onSignOut, getUserConfig } from './services';
import api from './api';
import './style.less';

const prefixCls = `inbiz-PersonalInfo`;
const tokenName = 'token';
export const personalDefault = {
  title: 'personalInfo.personSetting',
  tagName: 'setter',
  hide: false,
  isDel: false,
  isHide: true,
  isEdit: true,
  personConfig: [
    {
      id: 'basic',
      name: {
        value: 'PersonalInfo.baseConfig',
      },
      status: {
        value: true,
      },
      theme: '',
    },
    {
      id: 'theme',
      name: {
        value: 'PersonalInfo.themeConfig',
      },
      status: {
        value: false,
      },
      theme: {
        value: ['techblue', 'gray', 'deepskyblue', 'purple', 'deepblue'],
      },
    },
    {
      id: 'password',
      name: {
        value: 'PersonalInfo.setPassword',
      },
      status: {
        value: true,
      },
      theme: '',
    },
  ],
};

export interface PersonalInfoProps {
  /**
   * @description inbiz
   */
  inbiz?: any;
  /**
   * @description 类型
   */
  type?: string;
  /**
   * @description 视图类型
   */
  viewType: string;
  /**
   * @description 组件高度
   */
  height?: string | number;
  /**
   * @description 扩展样式名
   */
  className?: string;
  configList: any;
  onClick?: (e: any) => void;
  callBackEvents: {
    onBeforeSignOut?: (href: string) => Promise<string>;
  };
  emit?: (name: string) => void;
}

const PersonalInfo = (props: PersonalInfoProps, ref: any) => {
  const { viewType, height, className, callBackEvents, emit, inbiz } = props;

  const [configEvents] = useEvents(callBackEvents, emit);
  const appInfo = useApp();
  const [randomNum, $randomNum] = useState(Date.now()); // 头像多次请求处理
  const [visible, $setVisible] = useState(false); // 编辑用户信息
  const [userInfo, $setUserInfo] = useState(appInfo.userInfoByToken); // 用户信息
  const [configList, $configList] = useState(props.configList); // 用户信息
  const hooksByTheme = useState(
    appInfo?.SiteInfo?.UserTheme || appInfo?.SiteInfo?.Theme || 'techblue',
  ); // 选中的主题
  const hooksByPersonConfig = useState({}); // 个人配置
  const [personConfig, $personConfig] = hooksByPersonConfig;

  const getSystemMessage = useGetSystemMessageEffect();
  const langs = appInfo.Kinds ?? [];
  const getThemRequst = useGetThemeEffect(getOfficialPreview() ? 'preview' : '')
  const [themes, $themes] = useState([])

  // 注销
  const signOut = async () => {
    props.emit?.('onClick');
    const res = await onSignOut();
    const loginPageUrl = `${res?.loginurl || appInfo?.systemInfo?.loginPageUrl || '/api/auth/login'
      }?returnUrl=${location.href.replace(location.origin, '')}`;
    const url = (await configEvents.current.onBeforeSignOut?.(loginPageUrl)) ?? loginPageUrl;
    Cookies.remove(tokenName);
    // 搜索要求退出清除搜索条件
    localStorage.removeItem('_searchEngineStatus')
    sessionStorage.removeItem('_searchEngineStatus')
    window.location.href = url;
  };

  // 编辑信息
  const editInfo = () => {
    $setVisible(true);
  };

  // 获取用户信息
  const getUserInfo = async () => {
    const res = await getUserInfoBytoken();
    $setUserInfo(res.data);
  };

  // 获取多语言
  const getLangMessage = (langKey: string) => {
    getSystemMessage(langKey, () => {
      Cookies.set('lang', langToIntlKey(langKey));
    });
  };

  // 获取个人配置json
  const getPersonConfig = () => {
    getUserConfig({
      appId: appInfo.AppId,
      siteOutId: appInfo?.SiteInfo?.OutId,
    }).then((res) => {
      $personConfig(res);
    });
  };

  useEffect(() => {
    getPersonConfig();
    getThemRequst().then(({ themeList }) => {
      $themes(themeList)
    });
  }, []);

  useEffect(() => {
    let configList = props.configList.map((item: any) => {
      if (item.tagName == 'setter' && !item.personConfig) {
        return personalDefault;
      }
      return item;
    });
    $configList(configList);
  }, [props.configList]);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents),
      refreshUserInfo: getUserInfo
    }), []);

  const ContView =
    viewType == 'mini' ? (
      <SmallView
        userInfo={userInfo}
        getLangMessage={getLangMessage}
        {...props}
        langs={langs}
        signOut={signOut}
        editInfo={editInfo}
        random={randomNum}
      />
    ) : viewType == 'card' ? (
      <CardView
        userInfo={userInfo}
        getLangMessage={getLangMessage}
        {...props}
        langs={langs}
        signOut={signOut}
        editInfo={editInfo}
        random={randomNum}
      />
    ) : (
      <SimpleView
        {...props}
        configList={configList}
        getLangMessage={getLangMessage}
        signOut={signOut}
        hooksByTheme={hooksByTheme}
        langs={langs}
        themes={themes}
        userInfo={userInfo}
        editInfo={editInfo}
        random={randomNum}
      />
    );

  return (
    <div style={{ height: height || 'auto' }}>
      <div className={`${prefixCls} ${className}`}>{ContView}</div>

      {/* 这里必须渲染这个弹窗，应用皮肤切换的公共方法放里面了 */}
      <EditModal
        configList={configList}
        viewType={props?.viewType}
        userInfo={userInfo}
        getLangMessage={getLangMessage}
        langs={langs}
        visible={visible}
        hooksByTheme={hooksByTheme}
        hooksByPersonConfig={hooksByPersonConfig}
        onSubmit={() => {
          props.emit?.('onPersonInfoUpdate');
          getUserInfo();
          $setVisible(false);
        }}
        themes={themes}
        onCancel={() => $setVisible(false)}
        random={randomNum}
        onRandom={$randomNum}
      />
    </div>
  );
};

export default forwardRef(PersonalInfo);
